<template>
  <div class="app-container">
    <div class="main-container">
      <div class="page-header">
        <div class="header-left">
          <router-link to="/main/renshi/zhaoping/zhaopingxiudin" class="back-btn">
            <i class="el-icon-arrow-left"></i> 返回
          </router-link>
        </div>
        <div class="header-center">
          <h2 class="title">深圳市艾美思普科技有限公司</h2>
          <h3 class="subtitle">文件补发申请单</h3>
        </div>
        <div class="header-right">
          <template v-if="!isView">
            <el-button type="success" icon="el-icon-check" @click="saveData">保存</el-button>
            <el-button type="primary" icon="el-icon-printer" @click="printForm">打印</el-button>
            <el-button type="primary" icon="el-icon-view" @click="goToList">列表</el-button>
          </template>
        </div>
      </div>

      <div class="content-wrapper">
        <el-card v-for="(form, index) in [1, 2]" :key="index" class="form-card" shadow="hover">
          <el-form
            :ref="`form${index}`"
            :model="formData"
            :rules="rules"
            label-width="100px"
            :disabled="isView"
          >
            <div class="form-header">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="申请单位" prop="applicationUnit">
                    <el-input v-model="formData.applicationUnit" placeholder="请输入申请单位"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请日期" prop="applicationDate">
                    <el-date-picker
                      v-model="formData.applicationDate"
                      type="date"
                      placeholder="选择日期"
                      value-format="yyyy-MM-dd"
                      :picker-options="pickerOptions"
                      :clearable="false"
                      style="width: 100%">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <el-table
              :data="formData.files"
              border
              style="width: 100%"
              :header-cell-style="tableHeaderStyle"
              :cell-style="tableCellStyle"
            >
              <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
              <el-table-column label="文件编号" prop="fileNumber" min-width="120">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'files.' + scope.$index + '.fileNumber'"
                    :rules="rules.fileNumber"
                    class="no-margin"
                  >
                    <el-input v-model="scope.row.fileNumber" placeholder="请输入文件编号"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="文件名称" prop="fileName" min-width="180">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'files.' + scope.$index + '.fileName'"
                    :rules="rules.fileName"
                    class="no-margin"
                  >
                    <el-input v-model="scope.row.fileName" placeholder="请输入文件名称"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="版本" prop="version" width="180">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'files.' + scope.$index + '.version'"
                    :rules="rules.version"
                    class="no-margin"
                  >
                    <el-input v-model="scope.row.version" placeholder="请输入版本"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="数量（份）" prop="quantity" width="180">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'files.' + scope.$index + '.quantity'"
                    :rules="rules.quantity"
                    class="no-margin"
                  >
                    <el-input-number 
                      v-model="scope.row.quantity" 
                      :min="0" 
                      controls-position="right"
                      size="small">
                    </el-input-number>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="用途说明" prop="purpose" min-width="180">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'files.' + scope.$index + '.purpose'"
                    :rules="rules.purpose"
                    class="no-margin"
                  >
                    <el-input v-model="scope.row.purpose" placeholder="请输入用途说明"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" align="center">
                <template slot="header">
                  <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAddRow">新增行</el-button>
                </template>
                <template slot-scope="scope">
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="handleDeleteRow(scope.$index)"
                    :disabled="isView"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <div class="form-footer">
              <el-row :gutter="20" class="signature-row">
                <el-col :span="8">
                  <el-form-item label="核准" prop="approvedBy">
                    <el-input v-model="formData.approvedBy" placeholder="请输入核准人"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="审核" prop="reviewedBy">
                    <el-input v-model="formData.reviewedBy" placeholder="请输入审核人"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="经办" prop="handledBy">
                    <el-input v-model="formData.handledBy" placeholder="请输入经办人"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="文控中心处理意见" prop="documentControlOpinion" class="opinion-item">
                <el-input
                  type="textarea"
                  v-model="formData.documentControlOpinion"
                  :rows="3"
                  placeholder="请输入处理意见">
                </el-input>
              </el-form-item>

              <el-row :gutter="20" class="signature-row">
                <el-col :span="12">
                  <el-form-item label="签收" prop="signFor">
                    <el-input v-model="formData.signFor" placeholder="请输入签收人"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="发放" prop="distribution">
                    <el-input v-model="formData.distribution" placeholder="请输入发放人"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <div class="form-info">
                <span class="info-item">表单编号及版本：AM-FR-0005 A/0</span>
                <span class="info-item">生效日期：2006年10月30日</span>
                <span class="info-item">保存年限：长期</span>
              </div>
            </div>
          </el-form>
        </el-card>
      </div>
    </div>
    </div>
</template>

<script>
import { getFileReissueById, saveFileReissue } from '@/api/fileReissue'

export default {
  name: 'Wjbufa',
    data() {
        return {
      isView: false,
      pickerOptions: {
        disabledDate(time) {
          // 禁用未来日期和超过一年前的日期
          const today = new Date()
          const oneYearAgo = new Date()
          oneYearAgo.setFullYear(today.getFullYear() - 1)
          return time.getTime() > today.getTime() || time.getTime() < oneYearAgo.getTime()
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }, {
          text: '一个月前',
          onClick(picker) {
            const date = new Date()
            date.setMonth(date.getMonth() - 1)
            picker.$emit('pick', date)
          }
        }]
      },
            formData: {
                applicationUnit: '',
                applicationDate: '',
        files: Array(1).fill().map(() => ({
                        fileNumber: '',
                        fileName: '',
                        version: '',
                        quantity: 0,
                        purpose: ''
        })),
                approvedBy: '',
                reviewedBy: '',
                handledBy: '',
                documentControlOpinion: '',
                signFor: '',
                distribution: ''
      },
      rules: {
        applicationUnit: [
          { required: true, message: '请输入申请单位', trigger: 'blur' }
        ],
        applicationDate: [
          { required: true, message: '请选择申请日期', trigger: 'change' }
        ],
        fileNumber: [
          { required: true, message: '请输入文件编号', trigger: 'blur' }
        ],
        fileName: [
          { required: true, message: '请输入文件名称', trigger: 'blur' }
        ],
        version: [
          { required: true, message: '请输入版本', trigger: 'blur' }
        ],
        quantity: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          { type: 'number', min: 0, message: '数量必须大于等于0', trigger: 'blur' }
        ],
        purpose: [
          { required: true, message: '请输入用途说明', trigger: 'blur' }
        ]
      },
      tableHeaderStyle: {
        background: '#f5f7fa',
        color: '#303133',
        fontWeight: '600',
        height: '50px',
        padding: '0',
        textAlign: 'center'
      },
      tableCellStyle: {
        padding: '8px 0',
        textAlign: 'center'
      }
    }
  },
  created() {
    const { id, type } = this.$route.query
    this.isView = type === 'view'
    if (id) {
      this.getDetail(id)
    }
    },
    methods: {
    async getDetail(id) {
      try {
        const response = await getFileReissueById(id)
        const data  = response.data   
        // 如果有记录，使用第一条记录的数据
        if (data) {
          this.formData = {
            ...data,
            files: data.details || Array(1).fill().map(() => ({
              fileNumber: '',
              fileName: '',
              version: '',
              quantity: 0,
              purpose: ''
            }))
          }
        }
      } catch (error) {
        console.error('获取详情失败:', error)
        this.$message.error('获取详情失败')
      }
    },
    async saveData() {
      try {
        // 验证所有表单
        const validateForms = [0, 1].map(index => 
          this.$refs[`form${index}`][0].validate()
        )
        await Promise.all(validateForms)
        
        // 创建一个新的对象，将 files 重命名为 details
        const { files, ...otherData } = this.formData
        const saveData = {
          ...otherData,
          details: files.filter(file => file.fileNumber || file.fileName).map(file => ({
            ...file,
            quantity: Number(file.quantity) // 确保数量是数字类型
          }))
        }
        
        await saveFileReissue(saveData)
        this.$message.success('保存成功')
        this.$router.push('/main/biao/wjbufaList')
      } catch (error) {
        if (error.message) {
          this.$message.error(error.message)
        } else {
          this.$message.error('表单验证失败，请检查必填项')
        }
        console.error('保存失败:', error)
      }
    },
    goToList() {
      this.$router.push('/main/biao/wjbufaList')
    },  
    printForm() {
      window.print()
    },
    handleAddRow() {
            this.formData.files.push({
                fileNumber: '',
                fileName: '',
                version: '',
                quantity: 0,
                purpose: ''
      })
    },
    handleDeleteRow(index) {
      this.$confirm('确认删除该行数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formData.files.splice(index, 1)
        // 如果删除后没有行了，添加一个空行
        if (this.formData.files.length === 0) {
          this.handleAddRow()
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  // background-color: #f0f2f5;
  min-height: 100vh;
}

.main-container {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: #fff;
  padding: 16px 24px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

  .header-left, .header-right {
    min-width: 150px;
  }

  .header-center {
    flex: 1;
  text-align: center;

    .title {
      margin: 0 0 8px;
      color: #303133;
      font-size: 20px;
      font-weight: 600;
    }

    .subtitle {
      margin: 0;
      color: #606266;
      font-size: 16px;
      font-weight: 500;
    }
  }
}

.back-btn {
  text-decoration: none;
  color: #606266;
  font-size: 14px;
  display: flex;
  align-items: center;
  
  &:hover {
    color: #409EFF;
  }

  i {
    margin-right: 4px;
  }
}

.form-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-header {
  margin-bottom: 20px;
}

.form-footer {
  margin-top: 20px;

  .signature-row {
    margin: 20px 0;
  }

  .opinion-item {
    margin: 20px 0;
  }

  .form-info {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
    padding: 10px 20px;
    background-color: #f5f7fa;
    border-radius: 4px;

    .info-item {
      color: #606266;
      font-size: 14px;
    }
  }
}

:deep(.el-table) {
  .el-input, .el-input-number {
    width: 100%;
  }
}

::v-deep .no-margin .el-form-item__content .el-input{
  width: calc(100% + 100px);
  margin-left: -100px;
}

@media print {
  .app-container {
    padding: 0;
    background-color: #fff;
  }

  .page-header {
    .header-left, .header-right {
      display: none;
    }
  }

  .form-card {
    break-inside: avoid;
    box-shadow: none;
    page-break-after: always;

    &:last-child {
      page-break-after: auto;
    }
  }
}
</style>